package com.zcxk.web.handler;

import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.fastjson2.JSON;
import com.zcxk.common.MultiResponse;
import com.zcxk.constant.Constants;
import com.zcxk.dto.DeviceDTO;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author wangping
 * @date 2023-07-28 21:56
 */
public class GetActiveDevicesHandler implements Handler<RoutingContext> {

  private static final Logger logger = LoggerFactory.getLogger(GetActiveDevicesHandler.class);

  private WebClient client;

  public GetActiveDevicesHandler(WebClient client) {
    this.client = client;
  }

  @Override
  public void handle(RoutingContext ctx) {
    client.get(Constants.DCP_INTERFACE_ACTIVE_DEVICES).send().onSuccess(response -> {
        if (response.statusCode() != HttpResponseStatus.OK.code()) {
          logger.error("request to dcp server failed, interface: activeDevices, response code: {}", response.statusCode());
        } else {
          String result = response.bodyAsString();
          List<DeviceDTO> deviceDTOS = JSON.parseArray(result, DeviceDTO.class);
          ctx.json(MultiResponse.of(deviceDTOS));
        }
      })
      .onFailure(t -> {
        logger.error("request dcp server failure, interface: {}", Constants.DCP_INTERFACE_ACTIVE_DEVICES, t);
      });
  }

}
